<template>
  <div>

    <!-- 商品列表表格 -->
    <el-table :data="productList" stripe style="width: 100%">
      <el-table-column prop="name" label="商品名称" width="200" />
      <el-table-column prop="price" label="原价" width="150" />
      <el-table-column prop="discountPrice" label="折扣价" width="100" />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="num" label="总数" width="100" show-overflow-tooltip="true" />
      <el-table-column prop="bossName" label="商家" width="200" />
      <el-table-column label="操作" width="250" align="center">
        <template #default="scope">
          <el-button size="mini" type="danger" @click="deleteRestaurants(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination v-model:current-page="pagination.page" :page-size="pagination.size" :total="pagination.totalRecords"
      layout="total, prev, pager, next, sizes" @current-change="handlePageChange" @size-change="handleSizeChange"
      style="text-align: right; margin-top: 20px;" />

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

const productList = ref([]);

// 分页信息
const pagination = reactive({
  page: 1,
  size: 10,
  totalRecords: 0,
});


// 获取商品列表
const queryRestaurants = async () => {
  try {
    const response = await axios.get('/api/products/all', {
      params: { pageNum: pagination.page, pageSize: pagination.size }
    });
    if (response.data.code === 200) {
      productList.value = response.data.data.listData;
      pagination.totalRecords = response.data.data.totalRecords;
    }
  } catch (error) {
    ElMessage.error('获取用户数据失败');
  }
};

// 删除商品
const deleteRestaurants = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定删除此商品？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await axios.delete(`/api/products/${id}`);
    ElMessage.success('商品已删除');
    queryRestaurants(); // 更新商品列表
  } catch (error) {
    ElMessage.error('删除商品失败');
  }
};

// 处理分页页码变化
const handlePageChange = (newPage: number) => {
  pagination.page = newPage;
  queryRestaurants();
};

// 处理分页大小变化
const handleSizeChange = (newSize: number) => {
  pagination.size = newSize;
  pagination.page = 1; // 重置到第一页
  queryRestaurants();
};

// 页面加载时获取用户数据
onMounted(() => {
  queryRestaurants();
});

</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.el-table .el-button {
  margin-left: 8px;
}

.el-table .el-button:first-child {
  margin-left: 0;
}

.el-dialog .el-input,
.el-dialog .el-input-number {
  width: 100%;
}
</style>
